// packageApply/pages/statistics/statistics.js
const app = getApp();
import {
  deviceFind,
  refresh,
  getTotalRecord
} from "../../../public/api/device.js"
import {
  throttle,
  formatTime
} from "../../../utils/util"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    translations: {},
    language: '',
    uuid: "",
    show: false,
    maxDate: new Date().getTime(),
    minDate: '',
    chooseDate: '',
    option: {
      tooltip: {
        trigger: 'axis', // 鼠标悬浮在图表某个轴上的某个点时显示tooltip
        axisPointer: {
          type: 'cross', // 交叉指示器，能够同时显示 x 和 y 轴上的信息
          axis: 'x',
          crossStyle: {
            color: '#999' // 自定义交叉指示器的颜色
          }
        },
        formatter: function (params) {
          // 当触发 tooltip 时，格式化输出当前点的详细信息
          console.log(params);
          let content = `时间: ${params[0].name}`;
          params.forEach(param => {
            content += ` 值: ${param.value}`; // 显示 y 轴值及单位
          });
          return content;
        }
      },
      xAxis: {
        type: 'category',
        data: [], // 1月31日的日期数组
        axisLabel: {
          show: true,
          fontSize: 12, // 设置字体大小
          rotate: 45, // 旋转标签以避免重叠
          formatter: function (value) {
            return value.substring(5); // 只显示月-日，避免年重复显示
          }
        },
        boundaryGap: false, // 去除左右空白，折线图通常不需要边距
      },
      yAxis: {
        type: 'value',
        name: '数量',
        axisLabel: {
          formatter: '{value}', // 格式化Y轴标签
          fontSize: 12, // 设置字体大小
        }
      },
      dataZoom: [{
          type: 'inside',
          xAxisIndex: [0],
          start: 0,
          end: 100,
          show: false
        },
        {
          type: 'slider',
          xAxisIndex: [0],
          start: 0,
          end: 100,
          show: false
        }
      ],
      series: [{
        name: '数量',
        type: 'line', // 折线图
        data: [], 
        smooth: true, // 平滑折线
        lineStyle: {
          color: '#3398DB', // 折线颜色
          width: 2 // 折线宽度
        },
        itemStyle: {
          color: '#3398DB' // 数据点颜色
        }
      }],
      grid: {
        left: '10%',
        right: '10%',
        bottom: '20%',
        top: '20%',
      }
    },
    allData: {},
    currentData: 0,
    currentMonthData: 0,
    timer: null,
   
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // this.getDeviceDetail(options.uuid)
    let that = this
    this.setData({
      uuid: options.uuid
    })
    let chooseDate = formatTime(new Date()).slice(0,7).replace(/\//g, '-')
    let now = new Date()
    now.setMonth(now.getMonth() - 11)
    console.log(chooseDate);
    let timer = setInterval(() => {
      that.getRecord()
    },5 * 60 * 100)
    this.setData({
      chooseDate,
      minDate: now.getTime(),
      timer
    })
    this.getRecord(options.uuid)
  },

  getRecord(uuid) {
    let data = {}
    data.uuid = uuid ? uuid : this.data.uuid
    getTotalRecord(data).then(res => {
      if(res.data.code === 1) {
        let month = formatTime(new Date()).slice(0,7).replace(/\//g, '-')
        let day = formatTime(new Date()).split(" ")[0].slice(-2)
        let allData = JSON.parse(res.data.data.record ? res.data.data.record : {})
        console.log(allData);
        let currentData = allData[month] && allData[month][day] ? allData[month][day] : 0
        this.setData({
          allData,
          currentData
        })
        this.getChooseData()
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  },

  getChooseData() {
    let obj = this.data.allData[this.data.chooseDate]
    let keys = Object.keys(obj)
    let values = Object.values(obj)
    keys = keys.map(item => this.data.chooseDate + '-' + item)
    console.log(keys,values);
    let combined = keys.map((date, index) => {
      return { date, value: values[index] };
    });
    // 按照日期进行排序
    combined.sort((a, b) => new Date(a.date) - new Date(b.date));
    let sortedDates = combined.map(item => item.date);
    let sortedValues = combined.map(item => item.value);
    this.data.option.xAxis.data = sortedDates
    this.data.option.series[0].data = sortedValues
    let currentMonthData = values.reduce((accumulator, currentValue) => {
      return accumulator + currentValue;
    }, 0) 
    this.setData({
      option: this.data.option,
      currentMonthData
    })
  },

  getDeviceDetail(uuid) {
    let data = {}
    data.uuid = uuid
    deviceFind(data).then(res => {
      if (res.data.code === 1) {
        let info = res.data.data
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  },

  // 刷新设备
  doRefresh: throttle(function () {
    let data = {}
    data.uuid = this.data.uuid
    wx.showLoading({
      title: '刷新中',
    })
    refresh(data).then(res => {
      if (res.data.code === 1) {
        this.getRecord()
        wx.hideLoading()
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  }, 1500),

  openPopup: throttle(function() {
    this.setData({show: true})
  }, 1000),

  doCancel() {
    this.setData({show: false})
  },

  chooseDate(e) {
    let chooseDate = formatTime(new Date(e.detail)).slice(0,7).replace(/\//g, '-')
    console.log(chooseDate);
    this.setData({
      show: false,
      chooseDate
    })
    this.getChooseData()
  },

  goDetail() {
    wx.navigateTo({
      url: '../record/record?date=' + this.data.chooseDate + '&uuid=' + this.data.uuid,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const translations = app.globalData.translations;
    let language = wx.getStorageSync('language')
    this.setData({
      language,
      translations
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearInterval(this.data.timer)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})